<template>
  <div class="stopword-tab">
    <TabScaffold :current="page" :pageSize="pageSize" :total="total" :pageCount="pageData.length" :checkAll="checkAll"
      :pageSizeOptions="['10', '20', '25', '50']" @update:current="onPageChange" @update:pageSize="onPageSizeChange"
      @check-all="onCheckAll">
      <!-- 工具栏：左侧 -->
      <template #toolbar-left>
        <a-space>
          <a-button @click="onAdd">新增</a-button>
          <a-button :disabled="!selectedRowKeys.length" danger @click="confirmBatchDelete">批量删除</a-button>
          <a-button @click="onOpenImport">导入</a-button>
          <a-button :loading="exporting" @click="onOpenExport">导出</a-button>
        </a-space>
      </template>

      <!-- 工具栏：右侧 -->
      <template #toolbar-right>
        <a-input-search v-model:value="keyword" placeholder="输入自定义分词搜索" enter-button="搜索" allow-clear
          style="width: 260px" @search="onSearch" />
      </template>

      <!-- 表格 -->
      <a-table class="row40" :columns="columns" :data-source="pageData" :loading="loading" row-key="id"
        :pagination="false" :row-selection="rowSelection" bordered :customRow="onCustomRow">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'Original_word'">
            <!-- 改为纯文本，黑色显示 -->
            <span class="word-text">{{ record.Original_word }}</span>
          </template>

          <template v-else-if="column.key === 'status'">
            <span class="status-text" :class="record.status === 'published' ? 'ok' : 'off'">
              {{ record.status === "published" ? "启用" : "停用" }}
            </span>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-button type="link" class="op-link" @click="toEdit(record)">编辑</a-button>
            <span class="op-sep">|</span>
            <a-button type="link" danger class="op-link" @click="confirmSingleDelete(record)">删除</a-button>
            <span class="op-sep">|</span>
            <a-button type="link" class="op-link" :disabled="record.status !== 'published'"
              @click="onDisable(record)">停用</a-button>
            <span class="op-sep">|</span>
            <a-button type="link" class="op-link" :disabled="record.status === 'published'"
              @click="onEnable(record)">启用</a-button>
          </template>
        </template>
      </a-table>
    </TabScaffold>

    <!-- 导入 / 导出弹窗 -->
    <ImportModal v-model="importVisible" title="自定义分词导入" tip="说明：支持 CSV 或 JSON（UTF-8）。" @import="handleImport" />
    <ExportModal v-model="exportVisible" v-model:format="exportFormat" :loading="exporting" title="自定义分词导出"
      @confirm="handleExport" />
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, onMounted } from "vue";
import type { TableColumnsType } from "ant-design-vue";
import { Modal, message } from "ant-design-vue";
import { useRouter, useRoute } from "vue-router";

import TabScaffold from "@/components/TabScaffold.vue";
import ImportModal from "@/components/ImportModal.vue";
import ExportModal from "@/components/ExportModal.vue";

import {
  fetchCustomWordList,
  removeCustomWord,
  batchRemoveCustomWords,
  updateCustomWord,
  exportCustomWords,
  importCustomWordsByFile,
  type CustomWordItem,
  type ExportFormat,
} from "@/api/modules/customWords.api";

/** ======= 列表/分页/筛选 ======= */
const loading = ref(false);
const keyword = ref("");
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const data = ref<CustomWordItem[]>([]);
const pageData = computed(() => data.value);

/**
 * 载入列表
 */
async function loadList() {
  loading.value = true;
  try {
    let guard = 0;
    while (true) {
      const res = await fetchCustomWordList({
        page: page.value,
        pageSize: pageSize.value,
        keyword: keyword.value,
        sort: ["id"],
        excludeStatus: "archived",
      });
      data.value = res.list;
      total.value = res.total;

      const lastPage = Math.max(1, Math.ceil(total.value / pageSize.value));
      if (page.value > lastPage && page.value > 1 && guard < 3) {
        page.value = lastPage;
        guard++;
        continue;
      }
      if (page.value > 1 && data.value.length === 0 && guard < 3) {
        page.value = page.value - 1;
        guard++;
        continue;
      }
      break;
    }
  } finally {
    loading.value = false;
  }
}

function onSearch() {
  page.value = 1;
  loadList();
}
function onPageChange(p: number) {
  page.value = p;
  selectedRowKeys.value = [];
  loadList();
}
function onPageSizeChange(size: number) {
  pageSize.value = Number(size);
  page.value = 1;
  selectedRowKeys.value = [];
  loadList();
}

/** ======= 选择 ======= */
const selectedRowKeys = ref<Array<number | string>>([]);
const checkAll = computed(() => pageData.value.length > 0 && selectedRowKeys.value.length === pageData.value.length);
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: (string | number)[]) => (selectedRowKeys.value = keys as Array<number | string>),
}));
function onCheckAll(ev: any) {
  const checked = ev?.target?.checked ?? false;
  selectedRowKeys.value = checked ? pageData.value.map((x) => x.id) : [];
}

/** ======= 表头 ======= */
const columns = ref<TableColumnsType>([
  { title: "原词", dataIndex: "Original_word", key: "Original_word" },
  { title: "处理后词", dataIndex: "Processed_words", key: "Processed_words" },
  { title: "状态", dataIndex: "status", key: "status", width: 120 },
  { title: "操作", key: "actions", width: 260 },
]) as any;

/** ======= 跳转 ======= */
const router = useRouter();
const route = useRoute();
const currentAsRet = () => route.fullPath;

function onAdd() {
  router.push({ path: "/customWordSegmentationPage", query: { ret: currentAsRet() } });
}
function toEdit(record: CustomWordItem) {
  router.push({ path: "/customWordSegmentationPage", query: { id: String(record.id), ret: currentAsRet() } });
}
function toInfo(record: CustomWordItem) {
  router.push({ path: "/customWordSegmentationInfo", query: { id: String(record.id), ret: currentAsRet() } });
}

/** 整行点击（操作区与选择列除外） */
function onCustomRow(record: CustomWordItem) {
  return {
    onClick: (e: MouseEvent) => {
      const el = e.target as HTMLElement;
      // 排除：操作按钮区域、按钮自身、复选框（选择列）
      if (el.closest(".op-link") || el.closest(".ant-btn") || el.closest(".ant-checkbox-wrapper") || el.closest(".ant-checkbox")) {
        return;
      }
      toInfo(record);
    },
    style: { cursor: "pointer" },
  } as any;
}

/** ======= 删除 / 启用 / 停用 ======= */
function confirmSingleDelete(record: CustomWordItem) {
  Modal.confirm({
    title: "确认删除该记录？",
    content: `将删除：${record.Original_word ?? record.id}`,
    okText: "删除",
    cancelText: "取消",
    okType: "danger",
    async onOk() {
      await removeCustomWord(record.id);
      message.success("删除成功");
      await loadList();
    },
  });
}
function confirmBatchDelete() {
  if (!selectedRowKeys.value.length) return;
  const ids = selectedRowKeys.value.slice();
  Modal.confirm({
    title: "确认删除所选记录？",
    content: `共 ${ids.length} 条`,
    okText: "删除",
    cancelText: "取消",
    okType: "danger",
    async onOk() {
      await batchRemoveCustomWords(ids);
      message.success("删除成功");
      selectedRowKeys.value = [];
      await loadList();
    },
  });
}
async function onEnable(record: CustomWordItem) {
  if (record.status === "published") return;
  await updateCustomWord(record.id, { status: "published" });
  message.success("已启用");
  loadList();
}
async function onDisable(record: CustomWordItem) {
  if (record.status !== "published") return;
  await updateCustomWord(record.id, { status: "draft" });
  message.success("已停用");
  loadList();
}

/** ======= 导入 / 导出 ======= */
const importVisible = ref(false);
const exportVisible = ref(false);
const exporting = ref(false);
const exportFormat = ref<ExportFormat>("csv");

function onOpenImport() {
  importVisible.value = true;
}
function onOpenExport() {
  exportVisible.value = true;
}

function pickFile(payload: any): File | undefined {
  if (!payload) return undefined;
  if (payload instanceof File) return payload;
  if (payload.file instanceof File) return payload.file;
  if (payload.raw instanceof File) return payload.raw;
  if (payload.originFileObj instanceof File) return payload.originFileObj;
  if (Array.isArray(payload)) return payload[0] instanceof File ? payload[0] : undefined;
  if (Array.isArray(payload.files) && payload.files[0] instanceof File) return payload.files[0];
  if (Array.isArray(payload.fileList) && payload.fileList[0]?.originFileObj instanceof File) return payload.fileList[0].originFileObj;
  if (payload?.target?.files?.[0] instanceof File) return payload.target.files[0];
  return undefined;
}

async function handleImport(payload: any) {
  const file = pickFile(payload);
  if (!file) {
    message.warning("请选择要导入的文件");
    return;
  }
  const name: string = (file as any).name || "";
  const ext = name.split(".").pop()?.toLowerCase();
  const format = ext === "csv" ? "csv" : ext === "json" ? "json" : undefined;

  try {
    const res = await importCustomWordsByFile(file, { format });
    const inserted = res?.inserted ?? res?.created ?? 0;
    const updated = res?.updated ?? 0;
    const failed = res?.failed ?? res?.errors?.length ?? 0;

    message.success(`导入完成`);
    importVisible.value = false;
    selectedRowKeys.value = [];
    page.value = 1;
    loadList();
  } catch (e: any) {
    const code =
      e?.response?.data?.errors?.[0]?.extensions?.code ||
      e?.data?.errors?.[0]?.extensions?.code ||
      e?.code;
    if (code === "RECORD_NOT_UNIQUE") {
      message.error("检测到重复的值");
    } else {
      const msg =
        e?.response?.data?.errors?.[0]?.message ||
        e?.data?.errors?.[0]?.message ||
        e?.message ||
        "导入失败";
      message.error(msg);
    }
  }
}

/** 导出 */
async function handleExport(fmt?: ExportFormat) {
  const format: ExportFormat = fmt || exportFormat.value || "csv";
  exporting.value = true;
  try {
    const { filename, total: count } = await exportCustomWords({
      format,
      selectedIds: selectedRowKeys.value,
      keyword: keyword.value,
      excludeStatus: "archived",
      sort: ["id"],
    });
    message.success(`导出成功`);
    exportVisible.value = false;
  } catch (e: any) {
    message.error(e?.message || "导出失败");
  } finally {
    exporting.value = false;
  }
}

onMounted(loadList);
</script>

<style scoped>
/* 行高 40px */
.row40 :deep(.ant-table-thead > tr > th),
.row40 :deep(.ant-table-tbody > tr > td) {
  padding-top: 0 !important;
  padding-bottom: 0 !important;
  height: 40px !important;
  line-height: 40px !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

.row40 :deep(.ant-table-thead > tr),
.row40 :deep(.ant-table-tbody > tr) {
  height: 40px !important;
}

/* 视觉微调 */
.status-text.ok {
  color: #1f7a1f;
}

.status-text.off {
  color: #999;
}

.op-link {
  padding: 0;
}

.op-sep {
  color: #999;
  margin: 0 6px;
}

/* 原词：黑色文本 */
.word-text {
  color: #000;
}

</style>
